<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container" style="margin: 0">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="时间" style="width: 440px !important">
        <px-date-picker
          v-model="dateRange"
          type="monthrange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime"
        />
      </px-form-item>
      <px-form-item label="项目名称">
        <px-select v-model="queryParams.projectName" placeholder="请选择项目名称" clearable style="width: 220px" filterable>
          <px-option v-for="(dict, index) in ProjectNameList" :key="index" :label="dict" :value="dict" />
        </px-select>
      </px-form-item>
      <px-form-item label="负责人">
        <px-select v-model="queryParams.ownerName" placeholder="请选择负责人" clearable style="width: 220px" filterable>
          <px-option v-for="(dict, index) in OwnerNameList" :key="index" :label="dict" :value="dict" />
        </px-select>
      </px-form-item>
      <px-form-item label="厂商">
        <px-select v-model="queryParams.vendor" placeholder="请选择厂商" clearable style="width: 220px" filterable>
          <px-option v-for="(dict, index) in VendorList" :key="index" :label="dict" :value="dict" />
        </px-select>
      </px-form-item>
      <px-form-item label="品名">
        <px-select v-model="queryParams.productName" placeholder="请选择品名" clearable style="width: 220px" filterable>
          <px-option v-for="(dict, index) in ProductNameList" :key="index" :label="dict" :value="dict" />
        </px-select>
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>

    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button v-has="'WATER_REPORT_BUDGET_EXPORT'" type="primary" plain icon="" @click="handleExport">导出</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'WATER_REPORT_BUDGET_IMPORT'" type="primary" plain icon="" @click="handleimport">导入</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'WATER_REPORT_BUDGET_ADD'" type="primary" icon="" @click="handleAdd">新增项目</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'WATER_REPORT_BUDGET_EDITOR'" type="primary" plain icon="" :disabled="!(ids.length == 1)" @click="handleprojectEditor"
          >编辑项目</px-button
        >
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'WATER_REPORT_BUDGET_EDELETE'" type="primary" plain icon="" :disabled="multiple" @click="handleprojectdelete"
          >删除项目</px-button
        >
      </px-col>
    </px-row>

    <px-table
      v-if="!equipopen && !equipopenDetail"
      v-loading="loading"
      :data="typeList"
      height="calc(100vh - 359px)"
      show-overflow-tooltip
      :cell-style="cellStyle"
      :span-method="arraySpanMethod"
      border
      @selection-change="handleSelectionChange"
    >
      <px-table-column fixed="left" type="selection" width="40" />
      <!-- <px-table-column label="序号" width="60" align="center">
        <template #default="{ $index }">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </px-table-column> -->
      <px-table-column fixed="left" label="项目名称" width="170" prop="wasteName">
        <template #default="scope">
          <span>{{ scope.row.projectName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="负责人" width="150" prop="wasteType">
        <template #default="scope">
          <span>{{ scope.row.ownerName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="预算金额" width="85" prop="wasteCode">
        <template #default="scope">
          <span>{{ scope.row.budgetAmount }}</span>
        </template>
      </px-table-column>

      <px-table-column label="计划收货金额" width="115" prop="hazardCharacteristics">
        <template #default="scope">
          <span>{{ scope.row.planReceive }}</span>
        </template>
      </px-table-column>
      <px-table-column label="实际收货金额" width="115" prop="inboundTime">
        <template #default="scope">
          <span>{{ scope.row.actualReceive }}</span>
        </template>
      </px-table-column>
      <px-table-column label="预算执行率" width="200" prop="inboundTime">
        <template #default="scope">
          <div class="progressWrapper">
            <px-progress
              v-if="scope.row.budgetRate != null"
              style="margin-top: 10px"
              class="progress"
              :stroke-width="10"
              :color="scope.row.budgetRate >= 80 ? 'red' : '#10b981'"
              :percentage="scope.row.budgetRate == null ? 0.0 : scope.row.budgetRate.toFixed(2) < 0 ? 0 : scope.row.budgetRate.toFixed(2)"
            />
            <span v-else>-</span>
          </div>
          <!-- <span>{{ scope.row.budgetRate }}</span> -->
        </template>
      </px-table-column>
      <px-table-column label="PO单号" width="125" prop="container">
        <template #default="scope">
          <span>{{ scope.row.poOrderNumber }}</span>
        </template>
      </px-table-column>
      <px-table-column label="PO金额" width="75" prop="storageLocation">
        <template #default="scope">
          <span>{{ scope.row.poAmount }}</span>
        </template>
      </px-table-column>
      <px-table-column label="PO实际执行金额" width="140" prop="transportDepartment">
        <template #default="scope">
          <span>{{ scope.row.poActualAmount }}</span>
        </template>
      </px-table-column>
      <px-table-column label="PO执行周期" align="center">
        <px-table-column label="开始月份" width="130" prop="poStartTime">
          <template #default="scope">
            <span>{{ scope.row.poStartTime.slice(0, 7) }}</span>
          </template>
        </px-table-column>
        <px-table-column label="结束月份" width="130" prop="poEndTime">
          <template #default="scope">
            <span>{{ scope.row.poEndTime.slice(0, 7) }}</span>
          </template>
        </px-table-column>
      </px-table-column>
      <px-table-column label="厂商" width="195" prop="outboundStatus">
        <template #default="scope">
          <span>{{ scope.row.vendor }}</span>
        </template>
      </px-table-column>
      <px-table-column label="品名" width="145" prop="outboundStatus">
        <template #default="scope">
          <span>{{ scope.row.productName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="单价" width="80" prop="unitPrice">
        <template #default="scope">
          <span>{{ scope.row.unitPrice }}</span>
        </template>
      </px-table-column>
      <px-table-column label="数量" width="80" prop="quantity">
        <template #default="scope">
          <span>{{ scope.row.quantity }}</span>
        </template>
      </px-table-column>
      <px-table-column :label="listDate" align="center">
        <px-table-column label="收货数量" width="170" prop="receiveQuantity">
          <template #default="scope">
            <px-input-number
              v-if="scope.row.edittable"
              v-model="scope.row.receiveQuantity"
              style="width: 90px"
              controls-position="right"
              placeholder="请输入"
              clearable
              :min="0"
              :value-on-clear="0"
            />
            <px-button v-if="scope.row.edittable" style="margin-left: 5px" link type="primary" @click="closeedittable(scope.row)">
              <px-tooltip class="box-item" content="关闭" placement="top">
                <px-icon><CircleClose /></px-icon> </px-tooltip
            ></px-button>
            <px-button v-if="scope.row.edittable" style="margin-left: 5px" link type="primary" @click="editorreceiveQuantity(scope.row)">
              <px-tooltip class="box-item" content="保存" placement="top">
                <px-icon><Save /></px-icon> </px-tooltip
            ></px-button>
            <span v-else style="display: inline-block; width: 100%" @click="setedittable(scope.row)">{{
              scope.row.receiveQuantity != null ? scope.row.receiveQuantity : "-"
            }}</span>
          </template>
        </px-table-column>
        <px-table-column label="收货金额" width="91" prop="receiveAmount">
          <template #default="scope">
            <span>{{ scope.row.receiveAmount }}</span>
          </template>
        </px-table-column>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="120">
        <template #default="scope">
          <px-button v-has="'WATER_REPORT_BUDGET_LISTPO'" link type="primary" @click="handleDetail(scope.row)">
            <px-tooltip class="box-item" content="PO执行明细" placement="top">
              <px-icon><Tickets /></px-icon> </px-tooltip
          ></px-button>

          <px-button v-if="scope.row.closeFlag == 'Y'" v-has="'WATER_REPORT_BUDGET_SWITCH'" link type="primary" @click="switchchange(scope.row)">
            <px-tooltip class="box-item" content="开" placement="top">
              <px-icon><Unlock /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.closeFlag == 'N'" v-has="'WATER_REPORT_BUDGET_SWITCH'" link type="danger" @click="switchchange(scope.row)">
            <px-tooltip class="box-item" content="关" placement="top">
              <px-icon><Lock /></px-icon> </px-tooltip
          ></px-button>
          <!-- <px-switch
            v-if="scope.row.poDetailId"
            v-model="scope.row.closeFlag"
            v-has="'WATER_REPORT_BUDGET_SWITCH'"
            size="small"
            style="--px-switch-on-color: #13ce66; --px-switch-off-color: #ff4949"
            active-value="N"
            inactive-value="Y"
            @change="switchchange(scope.row)"
          /> -->
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->

    <px-scrollbar v-if="equipopenDetail" class="addEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
      <px-form
        ref="detailruleFormRef"
        :disabled="fromdisable"
        :rules="rules"
        :model="equipdata"
        :inline="true"
        class="demo-form-inline"
        label-width="160px"
      >
        <div class="box-card1" :style="{ height: jibenxinxiFlg == true ? '' : '42px' }">
          <div class="card-header" @click="setqingdanFlg()">
            <div class="card-title">项目信息</div>
            <div class="card-main">
              <px-icon v-if="!jibenxinxiFlg"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="8">
                <px-form-item label="项目名称" prop="projectName">
                  <px-input v-model="equipdata.projectName" placeholder="请输入项目名称" clearable /> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="负责人" prop="ownerId">
                  <px-select
                    v-model="equipdata.ownerId"
                    placeholder="请选择"
                    style="width: calc(100% - 100px)"
                    clearable
                    filterable
                    @change="changeresponsiblePerson"
                  >
                    <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" /> </px-select></px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="预算执行率">
                  <px-input v-model="equipdata.wasteType" :disabled="true" placeholder="预算执行率" clearable /> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="预算金额" prop="budgetAmount">
                  <px-input-number
                    v-model="equipdata.budgetAmount"
                    style="width: calc(100% - 100px)"
                    controls-position="right"
                    placeholder="请输入预算金额"
                    clearable
                  />
                  <!-- <span>{{ equipdata.wasteUnit }}</span> -->
                  <span style="margin-left: 16px">元</span>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="计划收货金额" prop="planReceive">
                  <px-input-number
                    v-model="equipdata.planReceive"
                    style="width: calc(100% - 100px)"
                    controls-position="right"
                    placeholder="请输入计划收货金额"
                    clearable
                  />
                  <!-- <span>{{ equipdata.wasteUnit }}</span> -->
                  <span style="margin-left: 16px"> 元</span>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="实际收货金额">
                  <px-input v-model="equipdata.wasteType" :disabled="true" placeholder="实际收货金额" clearable /> </px-form-item
              ></px-col>
            </px-row>
          </div>
        </div>
        <div class="box-card2" :style="{ height: jiqicanshuFlg == true ? '' : '42px' }">
          <div class="card-header" @click="setjiqicanshuFlg()">
            <div class="card-title">PO信息</div>
            <div class="card-main">
              <px-icon v-if="!jiqicanshuFlg"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div">
            <div class="form-table">
              <px-button type="primary" plain @click="handledelAdd">新增</px-button>
              <px-table style="margin-top: 16px" :data="equipdata.poList" height="280px" border>
                <px-table-column label="序号" width="80">
                  <template #default="scope">
                    <px-tooltip :content="scope.row.id" placement="top" effect="light">
                      <span>{{ scope.$index + 1 || "--" }}</span>
                    </px-tooltip>
                  </template>
                </px-table-column>

                <px-table-column label="PO单号" width="280" prop="poOrderNumber">
                  <template #default="scope">
                    <span><px-input v-model="scope.row.poOrderNumber" placeholder="请输入" /></span>
                  </template>
                </px-table-column>
                <px-table-column label="PO金额" prop="poAmount">
                  <template #default="scope">
                    <span><px-input-number v-model="scope.row.poAmount" controls-position="right" placeholder="请输入" /></span>
                  </template>
                </px-table-column>
                <px-table-column label="PO实际执行金额">
                  <template #default="scope">
                    <span><px-input-number v-model="scope.row.poActualAmount" controls-position="right" disabled placeholder="请输入" /></span>
                  </template>
                </px-table-column>
                <px-table-column label="PO执行开始时间" prop="poStartTime">
                  <template #default="scope">
                    <span>
                      <px-date-picker
                        v-model="scope.row.poStartTime"
                        style="width: 180px"
                        type="month"
                        placeholder="请选择"
                        format="YYYY-MM"
                        value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    </span>
                  </template>
                </px-table-column>
                <px-table-column label="PO执行结束时间" prop="poEndTime">
                  <template #default="scope">
                    <span>
                      <px-date-picker
                        v-model="scope.row.poEndTime"
                        style="width: 180px"
                        type="month"
                        placeholder="请选择"
                        format="YYYY-MM"
                        value-format="YYYY-MM-DD HH:mm:ss"
                      />
                    </span>
                  </template>
                </px-table-column>
                <px-table-column v-if="!fromdisable" label="操作" align="center" width="120">
                  <template #default="scope">
                    <!-- <px-button v-if="scope.row.status != 'INVALID'" link type="primary" @click="handleEditor(scope.row.checkContentId)">
                      <px-tooltip class="box-item" content="编辑" placement="top">
                        <px-icon><EditPen /></px-icon> </px-tooltip
                    ></px-button> -->
                    <px-button link type="danger" @click="handleDeletepo(scope.row)"
                      ><px-tooltip class="box-item" effect="light" content="删除" placement="top">
                        <px-icon><Delete /></px-icon> </px-tooltip
                    ></px-button>
                    <px-button v-if="scope.row.id" link type="primary" @click="handleDetailadd(scope.row)">
                      <px-tooltip class="box-item" content="PO明细" placement="top">
                        <px-icon><Tickets /></px-icon> </px-tooltip
                    ></px-button>
                  </template>
                </px-table-column>
                <template #empty>
                  <px-empty :image-size="150" />
                </template>
              </px-table>
            </div>
          </px-scrollbar>
        </div>
      </px-form>
    </px-scrollbar>
    <div v-if="equipopenDetail" v-loading="subLoading" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button v-if="fromdisable" type="primary" @click="equipopenDetailcancel">关闭</px-button>
      <px-button v-else type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="equipopenDetailsubmitForm(detailruleFormRef)"
        >保存</px-button
      >
    </div>
    <px-dialog v-model="polistVisible" draggable clickHideContent title="po执行明细" width="950" align-center>
      <px-form class="custom-form-ui">
        <px-form-item label="品名">
          <px-select v-model="DetailpoproductName" placeholder="请选择品名" clearable style="width: 220px" filterable>
            <px-option v-for="(dict, index) in ProductNameListdia" :key="index" :label="dict" :value="dict" />
          </px-select>
        </px-form-item>
        <px-form-item label="时间" style="float: left; width: 440px !important">
          <px-date-picker
            v-model="ForecastRange"
            type="monthrange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-button style="margin-top: 0" type="primary" icon="" @click="handleQueryForecast()">搜索</px-button>
      </px-form>
      <px-table style="margin-top: 16px" :summary-method="getSummaries" show-summary :data="polistVisibletalbe" border>
        <px-table-column label="品名" prop="productName">
          <template #default="scope">
            <span>
              {{ scope.row.productName }}
            </span>
          </template>
        </px-table-column>
        <px-table-column label="执行时间" prop="executeMonth">
          <template #default="scope">
            <span>
              {{ scope.row.executeMonth }}
            </span>
          </template>
        </px-table-column>
        <px-table-column label="执行数量" prop="executeQuantity">
          <template #default="scope">
            <span>
              <!-- {{ scope.row.executeQuantity }} -->
              <px-input-number
                v-if="scope.row.edittable"
                v-model="scope.row.executeQuantity"
                style="width: 90px"
                controls-position="right"
                placeholder="请输入"
                clearable
                :min="0"
                :value-on-clear="0"
              />
              <px-button v-if="scope.row.edittable" style="margin-left: 5px" link type="primary" @click="closeedittable(scope.row)">
                <px-tooltip class="box-item" content="关闭" placement="top">
                  <px-icon><CircleClose /></px-icon> </px-tooltip
              ></px-button>
              <px-button v-if="scope.row.edittable" style="margin-left: 5px" link type="primary" @click="editorreceiveQuantity2(scope.row)">
                <px-tooltip class="box-item" content="保存" placement="top">
                  <px-icon><Save /></px-icon> </px-tooltip
              ></px-button>
              <span v-else style="display: inline-block; width: 100%" @click="setedittable2(scope.row)">{{
                scope.row.executeQuantity != null ? scope.row.executeQuantity : "-"
              }}</span>
            </span>
          </template>
        </px-table-column>
        <px-table-column label="执行金额" prop="executeAmount">
          <template #default="scope">
            <span>
              {{ scope.row.executeAmount }}
            </span>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
    </px-dialog>
    <px-dialog v-model="addpolistVisible" draggable clickHideContent title="po明细" width="1250" align-center>
      <px-button type="primary" plain @click="handledelAddpo">新增</px-button>
      <px-table style="margin-top: 16px" :data="poListDetail" height="280px" border>
        <px-table-column label="序号" width="80">
          <template #default="scope">
            <px-tooltip :content="scope.row.id" placement="top" effect="light">
              <span>{{ scope.$index + 1 || "--" }}</span>
            </px-tooltip>
          </template>
        </px-table-column>

        <px-table-column label="厂商" prop="poOrderNumber">
          <template #default="scope">
            <span>
              <px-select v-model="scope.row.vendor" placeholder="请选择厂商" clearable filterable>
                <px-option v-for="dict in salesCompanyList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemName" />
              </px-select>
            </span>
          </template>
        </px-table-column>
        <px-table-column label="品名" prop="poAmount">
          <template #default="scope">
            <span>
              <px-tree-select
                v-if="projectType == 'chemical'"
                v-model="scope.row.productNumber"
                clearable
                style="width: 100%"
                placeholder="请选择化学品"
                :props="defaultProps"
                filterable
                :data="productNameList"
                :render-after-expand="false"
                collapse-tags
                collapse-tags-tooltip
                @change="handleNodeChange(scope.row)"
                @node-click="nodeClick"
              />
              <px-input v-if="projectType == 'sparePart'" :value="scope.row.productName" disabled style="width: 100px" placeholder="品名" clearable />
              <px-button
                v-if="projectType == 'sparePart'"
                size="small"
                style="position: absolute; top: 6px; right: 13px"
                type="primary"
                @click="setproductName(scope.row)"
              >
                选择
              </px-button>
              <px-tree-select
                v-if="projectType == 'waste'"
                v-model="scope.row.productNumber"
                clearable
                style="width: 100%"
                placeholder="请选择废弃物"
                :props="defaultProps"
                filterable
                :data="productNameList"
                :render-after-expand="false"
                collapse-tags
                collapse-tags-tooltip
                @change="handleNodeChange(scope.row)"
                @node-click="nodeClick"
              />
              <px-input v-if="projectType == 'other'" v-model="scope.row.productName" placeholder="请输入" />
            </span>
          </template>
        </px-table-column>
        <px-table-column label="单价(元)">
          <template #default="scope">
            <span><px-input-number v-model="scope.row.unitPrice" controls-position="right" placeholder="请输入" /></span>
          </template>
        </px-table-column>
        <px-table-column label="数量">
          <template #default="scope">
            <span><px-input-number v-model="scope.row.quantity" controls-position="right" placeholder="请输入" /></span>
          </template>
        </px-table-column>
        <px-table-column v-if="!fromdisable" label="操作" align="center" width="120">
          <template #default="scope">
            <!-- <px-button v-if="scope.row.status != 'INVALID'" link type="primary" @click="handleEditor(scope.row.checkContentId)">
                      <px-tooltip class="box-item" content="编辑" placement="top">
                        <px-icon><EditPen /></px-icon> </px-tooltip
                    ></px-button> -->
            <px-button link type="danger" @click="handleDeletepolist(scope.row)"
              ><px-tooltip class="box-item" effect="light" content="删除" placement="top">
                <px-icon><Delete /></px-icon> </px-tooltip
            ></px-button>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="addpolistVisible = false">取消</px-button>
          <px-button type="primary" @click="addeoplist()"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>
    <measure v-if="measureShow" @close="measureclose" @setmeasure="setmeasureValue" />
    <px-dialog v-model="dialogVisible" draggable clickHideContent title="导入数据" :width="600" :before-close="handelClose">
      <div class="import-bottle">
        <div class="import-bottle-upload">
          <div class="import-bottle-title">
            上传前请先
            <!-- <span class="download" @click="downloadFn"> 下载模板 </span> -->
            <a :href="fsxlsx" download="导入模板.xlsx"><span class="download"> 下载模板 </span></a>
            ，填写完成后导入数据
          </div>
          <importFiles
            ref="dialogSuccess"
            v-model="importFile"
            :upfileid="projectType"
            :isNotImmediateUpload="false"
            :uploadApi="projectuploadFile"
            @submit="submitHandler"
          />
        </div>
      </div>
    </px-dialog>
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({ name: "SystemDataDict" });
const props = defineProps({ projectType: { type: String, default: "chemical" } });
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { userlistPage } from "@/api/waterQualityDetection";
import { useRouter, useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";
import measure from "./components/measure.vue";
import importFiles from "./importFiles.vue";
import {
  hazardWasteInqueryWasteFuture,
  queryListPagepush,
  queryDetailpush,
  addpush,
  updatepush,
  deletepush,
  queryBatchOutInfopull
} from "@/api/hazardousWasteS";
import {
  projectadd,
  projectupdate,
  projectdelete,
  projectqueryDetail,
  projectqueryListPage,
  projectqueryDropDownProjectName,
  projectqueryDropDownOwnerName,
  projectqueryDropDownProductName,
  projectqueryDropDownVendor,
  poDetailExecutequeryList,
  poDetailqueryChemicalProductName,
  poDetailqueryWasteProductName,
  poupdate,
  poqueryInfo,
  poDetailExecutequeryDropDownProductName,
  projectupdateReceiveQuantity,
  poDetailExecuteupdateExecuteQuantity,
  projectupdateCloseFlag,
  projectuploadFile
} from "@/api/water/budget";
const jibenxinxiFlg = ref(true);
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const measureShow = ref(false);
const setproductNamerow = ref({});
const importFile = ref("");
const submitHandler = val => {
  console.log(val);
  PxMessage({
    message: "数据导入成功",
    type: "success"
  });
};
const setproductName = row => {
  measureShow.value = true;
  setproductNamerow.value = row;
};
const measureclose = val => {
  measureShow.value = val;
};
const setmeasureValue = val => {
  measureShow.value = false;
  if (val) {
    console.log(val);
    setproductNamerow.value.productName = val.sparePartName;
    setproductNamerow.value.productNumber = val.sparePartCode;
  }
};
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 12 || columnIndex === 13 || columnIndex === 14 || columnIndex === 15 || columnIndex === 16 || columnIndex === 17) {
    console.log(row);
    if (row.closeFlag !== null) {
      if (row.closeFlag == "Y") {
        return { background: "#ccc !important" };
      }
    }
  } else {
    return {};
  }
  // return { background: "#FFDADA" };
};
const poListDetail = ref([]);
// {
//   id: null,
//   poDetailList: [
//     {
//       id: null,
//       projectNumber: "",
//       poNumber: "",
//       poDetailNumber: "",
//       vendor: "",
//       productNumber: "",
//       productName: "",
//       unitPrice: null,
//       quantity: null
//     }
//   ],
//   deletePoDetailIds: []
// }
const handleexport = () => {};
const dialogVisible = ref(false);
const handleimport = () => {
  dialogVisible.value = true;
};
const handledelAddpo = () => {
  poListDetail.value.push({
    id: null,
    projectNumber: "",
    poNumber: "",
    poDetailNumber: "",
    vendor: "",
    productNumber: "",
    productName: "",
    unitPrice: null,
    quantity: null
  });
};
const deletePoDetailIds = ref([]);
const addeoplist = () => {
  poupdate({
    id: handleDetailaddrow.value.id,
    poDetailList: poListDetail.value,
    deletePoDetailIds: deletePoDetailIds.value
  }).then(res => {
    console.log(res);
    PxMessage({
      message: "保存成功",
      type: "success"
    });
    addpolistVisible.value = false;
  });
};
const handleDeletepolist = row => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    // type: "warning",
    draggable: true
  })
    .then(async () => {
      poListDetail.value = poListDetail.value.filter(item => item != row);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      if (row.id) {
        deletePoDetailIds.value.push(row.id);
      }
    })
    .catch(() => {});
};
const handledelAdd = () => {
  equipdata.value.poList.push({
    id: "",
    projectNumber: "",
    poNumber: "",
    poOrderNumber: "",
    poAmount: "",
    poStartTime: "",
    poEndTime: "",
    poActualAmount: ""
  });
};
const nameSpanMap = ref({});
const poSpanMap = ref({});
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (
    columnIndex === 0 ||
    columnIndex === 1 ||
    columnIndex === 2 ||
    columnIndex === 3 ||
    columnIndex === 4 ||
    columnIndex === 5 ||
    columnIndex === 6
  ) {
    if (nameSpanMap.value[row.projectName] && rowIndex === nameSpanMap.value[row.projectName].rowIndex) {
      return {
        rowspan: nameSpanMap.value[row.projectName].rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
  if (columnIndex === 7 || columnIndex === 8 || columnIndex === 9 || columnIndex === 10 || columnIndex === 11) {
    if (poSpanMap.value[row.poOrderNumber] && rowIndex === poSpanMap.value[row.poOrderNumber].rowIndex) {
      return {
        rowspan: poSpanMap.value[row.poOrderNumber].rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
const router = useRouter();
const jiqicanshuFlg = ref(true);
const polistVisible = ref(false);
const addpolistVisible = ref(false);
const wasteUnit = ref("%");
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const shebeitaizhangFlg = ref(true);
const setshebeitaizhangFlg = () => {
  shebeitaizhangFlg.value = !shebeitaizhangFlg.value;
};
const moxingshezhiFlg = ref(true);
const setmoxingshezhiFlg = () => {
  moxingshezhiFlg.value = !moxingshezhiFlg.value;
};
const setreceiveCompanyCode = val => {
  let setvalue = null;
  setvalue = liquidList.value.find(option => option.itemValue == val);
  console.log(setvalue);
  if (setvalue && setvalue?.itemDesc != "") {
    equipdata.value.wasteType = JSON.parse(setvalue.itemDesc).type;
    equipdata.value.wasteCode = JSON.parse(setvalue.itemDesc).code;
    equipdata.value.hazardCharacteristics = JSON.parse(setvalue.itemDesc).tx;
    equipdata.value.container = JSON.parse(setvalue.itemDesc).container;
    equipdata.value.storageLocation = JSON.parse(setvalue.itemDesc).storage;
  } else {
    equipdata.value.wasteType = "";
    equipdata.value.wasteCode = "";
    equipdata.value.hazardCharacteristics = "";
    equipdata.value.container = "";
    equipdata.value.storageLocation = "";
  }

  //console.log(setvalue);
};

const setAddreceiveCompanyCode = val => {
  let setvalue = null;
  setvalue = liquidList.value.find(option => option.itemValue == val);
  if (setvalue && setvalue.itemDesc != "") {
    equipdata.value.receiveCompanyCode = JSON.parse(setvalue.itemDesc).receiveCompanyCode;
  } else {
    // equipdata.value.receiveCompanyCode = "";
  }
  //console.log(setvalue);
};
const route = useRoute();
const salesCompanyList = ref([]);
const productNameList = ref([]);
const defaultProps = {
  children: "children",
  label: "productName",
  // label: "productNameBySystem",
  value: "productNumber"
};
const fsxlsx = ref("");
onMounted(() => {
  getPreviousMonth();

  if (props.projectType == "chemical") {
    fsxlsx.value = proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/预算项目导入模板_化学品.xlsx`);
    poDetailqueryChemicalProductName({}).then(res => {
      console.log(res);
      productNameList.value = res;
    });
    queryChildByTypeCodeAndItemValue({
      value: "WATER_CHEMICAL_SUPPLIER",
      typeCode: "WTTS"
    }).then((response: any) => {
      //console.log(response);
      salesCompanyList.value = response;
    });
  }
  if (props.projectType == "sparePart") {
    fsxlsx.value = proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/预算项目导入模板_备件耗材.xlsx`);
    poDetailqueryWasteProductName({}).then(res => {
      console.log(res);
      productNameList.value = res;
    });
    queryChildByTypeCodeAndItemValue({
      value: "VENDOR_SPARE_PART",
      typeCode: "WATER_BUDGET_VENDOR"
    }).then((response: any) => {
      //console.log(response);
      salesCompanyList.value = response;
    });
  }
  if (props.projectType == "waste") {
    fsxlsx.value = proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/预算项目导入模板_废弃物.xlsx`);
    poDetailqueryWasteProductName({}).then(res => {
      console.log(res);
      productNameList.value = res;
    });
    queryChildByTypeCodeAndItemValue({
      value: "RU01",
      typeCode: "WTTS"
    }).then((response: any) => {
      //console.log(response);
      salesCompanyList.value = response;
    });
  }
  if (props.projectType == "other") {
    fsxlsx.value = proxy.useGetStaticUrl(`/ifp-web-static/file/xlsx/预算项目导入模板_其他.xlsx`);
    poDetailqueryWasteProductName({}).then(res => {
      console.log(res);
      productNameList.value = res;
    });
    queryChildByTypeCodeAndItemValue({
      value: "VENDOR_OTHER",
      typeCode: "WATER_BUDGET_VENDOR"
    }).then((response: any) => {
      //console.log(response);
      salesCompanyList.value = response;
    });
  }
});

const handleNodeChange = row => {
  setTimeout(() => {
    row.productName = selectTree.value.productName;
    row.productName = selectTree.value.productNameBySystem;
  }, 300);
};
const selectTree = ref({});
const nodeClick = (e1emData, nodeData) => {
  console.log(e1emData, nodeData);
  selectTree.value = e1emData;
};
const listDate = ref("");
function getPreviousMonth() {
  const currentDate = new Date(); // 获取当前日期
  let year = currentDate.getFullYear();
  let month = currentDate.getMonth(); // 月份从0开始，0表示1月

  if (month === 0) {
    // 如果当前月份是1月
    year -= 1; // 年份减1
    month = 12; // 月份设置为12月
  } else {
    month -= 1; // 月份减1
  }

  const previousMonthDate = new Date(year, month, 1); // 获取前一个月的第一天
  // return previousMonthDate;
  listDate.value = `${previousMonthDate.getFullYear()}年${previousMonthDate.getMonth() + 1}月`;
}
const { proxy }: any = getCurrentInstance();

const typeList = ref([]);
const detailruleFormRef = ref();
const progressVisible = ref(false);
const open = ref(false);
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const progressPercent = ref(0);
const dateRange = ref([]);

// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
const editorreceiveQuantity = row => {
  console.log(row);
  if (row.receiveQuantity != null) {
    projectupdateReceiveQuantity({
      poDetailId: row.poDetailId,
      poDetailExecuteId: row.poDetailExecuteId,
      receiveQuantity: row.receiveQuantity
    }).then(res => {
      PxMessage({
        message: "修改成功",
        type: "success"
      });
      getList();
    });
  } else {
    row.receiveQuantity = 0;
  }
};
const editorreceiveQuantity2 = row => {
  console.log(row);
  if (row.executeQuantity != null) {
    poDetailExecuteupdateExecuteQuantity({
      projectNumber: row.projectNumber,
      poNumber: row.poNumber,
      poDetailNumber: row.poDetailNumber,
      executeMonth: row.executeMonth,
      executeQuantity: row.executeQuantity
    }).then(res => {
      PxMessage({
        message: "修改成功",
        type: "success"
      });
      getList();
      handleQueryForecast();
    });
  } else {
    row.executeQuantity = 0;
  }
};
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
const Futurerow = ref({});

const handleQueryForecast = () => {
  // if (ForecastRange.value.length > 0) {
  // } else {
  //   PxMessage({ message: "请选择预测时间", type: "error" });
  // }
  poDetailExecutequeryList({
    startTime: ForecastRange.value[0],
    endTime: ForecastRange.value[1],
    poNumber: handleDetailpo.value.poNumber,
    productName: DetailpoproductName.value
  }).then(res => {
    chartList.value = res.futureData;
    polistVisibletalbe.value = res;
    polistVisibletalbe.value.map(item => (item.edittable = false));
    setTimeout(() => {
      progressVisible.value = true;
    }, 200);
  });
};

const waterstatusList = [
  { value: "VALID", name: "全部" },
  { value: "INVALID", name: "已删除" }
];
const buttonTitle = ref("");
const changeresponsiblePerson = val => {
  userList.value.forEach(item => {
    if (item.value == val) {
      console.log(item);
      equipdata.value.ownerName = item.label;
    }
  });
};
const changePhotoList = val => {
  equipdata.value.weighingFile = val;
  console.log(val);
};
const changeFileList = val => {
  equipdata.value.attachment = val;
  console.log(val);
};
const data = reactive({
  liquidList: [],
  userList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  equipmentDeptList: [],
  modelIdList: [],
  chukuList: [],
  form: {},
  wasteUnitoptions: [{ value: "%", label: "%" }],
  photoStatusFlag: false,
  fileStatusFlag: false,
  equipdata: {
    projectNumber: "",
    projectName: "",
    projectType: props.projectType,
    ownerId: "",
    ownerName: "",
    budgetAmount: "",
    planReceive: "",
    poList: [
      {
        id: "",
        projectNumber: "",
        poNumber: "",
        poOrderNumber: "",
        poAmount: "",
        poStartTime: "",
        poEndTime: "",
        poActualAmount: ""
      }
    ]
  },
  queryParams: {
    projectType: props.projectType,
    pageNum: 1,
    pageSize: 20,
    startDate: "",
    endDate: "",
    projectName: "",
    ownerName: "",
    vendor: "",
    productName: ""
  },
  rules: {
    ownerId: [{ required: true, message: "负责人不能为空", trigger: "change" }],
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    budgetAmount: [{ required: true, message: "预算金额不能为空", trigger: "blur" }],
    planReceive: [{ required: true, message: "计划收货金额不能为空", trigger: "blur" }]
  },
  headers: { Authorization: "Bearer " + getToken().accessToken || "" },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  chartList: [],
  ForecastRange: [],
  Futureid: ""
});

const {
  Futureid,
  ForecastRange,
  chartList,
  userList,
  liquidList,
  chukuList,
  queryParams,
  form,
  rules,
  equipdata,
  equipmentTypeList,
  modelIdList,
  photoStatusFlag,
  fileStatusFlag,
  wasteUnitoptions
} = toRefs(data);
const checkTime = () => {
  if (equipdata.value.manufactureDate && equipdata.value.warrantyEndDate) {
    if (equipdata.value.manufactureDate > equipdata.value.warrantyEndDate) {
      PxMessage({ message: "开始时间不能大于结束时间", type: "error" });
    }
  }
};
import { receiveNamedanger } from "@/api/waterClass";
const ProjectNameList = ref([]);
const OwnerNameList = ref([]);
const ProductNameList = ref([]);
const VendorList = ref([]);
const getqueryCategoryList = () => {
  userlistPage({ page: 1, pageSize: 9999, deptNameList: ["WATER"], status: 0 }).then((response: any) => {
    userList.value = response.data.map(item => ({ label: `${item.username}-${item.realName}`, value: item.userId }));
    console.log(response);
  });
  projectqueryDropDownProjectName({ projectType: props.projectType }).then(res => {
    console.log(res);
    ProjectNameList.value = res;
  });
  projectqueryDropDownOwnerName({ projectType: props.projectType }).then(res => {
    console.log(res);
    OwnerNameList.value = res;
  });
  projectqueryDropDownProductName({ projectType: props.projectType }).then(res => {
    console.log(res);
    ProductNameList.value = res;
  });
  projectqueryDropDownVendor({ projectType: props.projectType }).then(res => {
    console.log(res);
    VendorList.value = res;
  });
};
getqueryCategoryList();
function getList() {
  loading.value = true;
  if (dateRange.value != null) {
    queryParams.value.startDate = dateRange.value[0];
    queryParams.value.endDate = dateRange.value[1];
  } else {
    queryParams.value.startDate = "";
    queryParams.value.endDate = "";
  }

  projectqueryListPage(queryParams.value).then((response: any) => {
    nameSpanMap.value = {};
    poSpanMap.value = {};
    let currentSpan = 0;
    let dataList = response.data;
    if (dataList == null) {
      typeList.value = [];
      loading.value = false;
      return;
    }
    if (dataList != null && dataList.length > 0) {
      dataList.forEach((row, index) => {
        console.log(index);
        if (index === 0 || dataList[index - 1].projectName !== row.projectName) {
          currentSpan = 1;
          nameSpanMap.value[row.projectName] = {
            rowIndex: index,
            rowspan: 1
          };
        } else {
          currentSpan++;
          nameSpanMap.value[row.projectName].rowspan = currentSpan;
        }
      });
      dataList.forEach((row, index) => {
        console.log(index);
        if (index === 0 || dataList[index - 1].poOrderNumber !== row.poOrderNumber) {
          currentSpan = 1;
          poSpanMap.value[row.poOrderNumber] = {
            rowIndex: index,
            rowspan: 1
          };
        } else {
          currentSpan++;
          poSpanMap.value[row.poOrderNumber].rowspan = currentSpan;
        }
      });
    }
    typeList.value = dataList;
    typeList.value.map(item => (item.edittable = false));
    total.value = response.total;
    loading.value = false;
  });
}
const setedittable = row => {
  if (row.receiveQuantity != null) {
    typeList.value.map(item => (item.edittable = false));
    row.edittable = true;
  }
};
const setedittable2 = row => {
  polistVisibletalbe.value.map(item => (item.edittable = false));
  row.edittable = true;
};
const closeedittable = row => {
  row.edittable = false;
};
/** 取消按钮 */
function cancel() {
  equipopen.value = false;
}
function equipopenDetailcancel() {
  equipopenDetail.value = false;
  getList();
}
/** 表单重置 */
function reset() {
  form.value = { id: undefined, dictionaryName: undefined, dictionaryType: undefined, status: "VALID", remarks: undefined };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    projectType: props.projectType,
    startDate: "",
    endDate: "",
    projectName: "",
    ownerName: "",
    vendor: "",
    productName: ""
  };
  dateRange.value = [];
  handleQuery("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipmentTypeList.value = [];
  modelIdList.value = [];
  equipdata.value = {
    projectNumber: "",
    projectName: "",
    projectType: props.projectType,
    ownerId: "",
    ownerName: "",
    budgetAmount: "",
    planReceive: "",
    poList: [
      {
        id: "",
        projectNumber: "",
        poNumber: "",
        poOrderNumber: "",
        poAmount: "",
        poStartTime: "",
        poEndTime: "",
        poActualAmount: ""
      }
    ]
  };
}
function handleDeletepo(row) {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    // type: "warning",
    draggable: true
  })
    .then(async () => {
      equipdata.value.poList = equipdata.value.poList.filter(item => item != row);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      if (buttonTitle.value == "编辑") {
        deletePoIds.value.push(row.id);
      }
    })
    .catch(() => {});
}
const handleDetailpo = ref({});
const DetailpoproductName = ref("");
const ProductNameListdia = ref([]);
const polistVisibletalbe = ref([]);

const getSummaries = param => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "N/A";
    }
  });

  return sums;
};
const handleDetail = row => {
  ForecastRange.value = [];
  console.log(row);
  handleDetailpo.value = row;
  if (row.productName) {
    DetailpoproductName.value = row.productName;
  }
  poDetailExecutequeryList({
    poNumber: row.poNumber,
    productName: row.productName
  }).then(res => {
    console.log(res);
    polistVisible.value = true;
    polistVisibletalbe.value = res;
    polistVisibletalbe.value.map(item => (item.edittable = false));
    poDetailExecutequeryDropDownProductName({
      poNumber: row.poNumber
    }).then(res => {
      console.log(res);
      ProductNameListdia.value = res;
    });
  });
};
const handleDetailaddrow = ref({});
const handleDetailadd = row => {
  console.log(row);
  poListDetail.value = [];
  handleDetailaddrow.value = row;
  poqueryInfo({
    id: row.id
  }).then(res => {
    console.log(res);
    poListDetail.value = res.poDetailList;
    addpolistVisible.value = true;
    deletePoDetailIds.value = [];
  });
};
const handleCopy = async val => {
  buttonTitle.value = "新增";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;

  const data = await queryDetailpush({ id: val });
  //console.log(data);
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipdata.value = data;
  equipdata.value.receiverId = Number(data.receiverId);
  equipdata.value.inboundTime = "";
};

const handleEditor = async val => {
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;

  const data = await queryDetailpush({ id: val });
  //console.log(data);
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipdata.value = data;
  equipdata.value.receiverId = Number(data.receiverId);
};
/** 多选框选中数据 */
const nums = ref([]);
function handleSelectionChange(selection) {
  chukuList.value = selection;
  ids.value = selection.map(item => item.projectId);
  nums.value = selection.map(item => item.projectNumber);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const switchchange = row => {
  console.log(row);
  projectupdateCloseFlag({
    poId: row.poId,
    poDetailId: row.poDetailId,
    operate: row.closeFlag == "Y" ? "open" : "close"
  }).then(res => {
    PxMessage({
      message: "修改成功",
      type: "success"
    });
    getList();
  });
};
const handleprojectdelete = () => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      projectdelete({
        projectNumberList: nums.value
      }).then(res => {
        PxMessage({
          message: "删除成功",
          type: "success"
        });
        getList();
      });
    })
    .catch(() => {});
};
const deletePoIds = ref([]);
/** 提交按钮 */
const subLoading = ref(false);
const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      subLoading.value = true;
      const params = {
        id: equipdata.value.id,
        projectNumber: equipdata.value.projectNumber,
        projectName: equipdata.value.projectName,
        projectType: equipdata.value.projectType,
        ownerId: equipdata.value.ownerId,
        ownerName: equipdata.value.ownerName,
        budgetAmount: equipdata.value.budgetAmount,
        planReceive: equipdata.value.planReceive,
        poList: equipdata.value.poList
      };
      if (buttonTitle.value == "新增") {
        // if (params.weighingFile.length > 0) {
        //   params.weighingFile = params.weighingFile.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        // }
        // if (params.attachment.length > 0) {
        //   params.attachment = params.attachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        // }
        const params = {
          id: equipdata.value.id,
          projectNumber: equipdata.value.projectNumber,
          projectName: equipdata.value.projectName,
          projectType: equipdata.value.projectType,
          ownerId: equipdata.value.ownerId,
          ownerName: equipdata.value.ownerName,
          budgetAmount: equipdata.value.budgetAmount,
          planReceive: equipdata.value.planReceive,
          poList: equipdata.value.poList,
          deletePoIds: deletePoIds.value
        };
        projectadd(params)
          .then((response: any) => {
            PxMessage({ message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`, type: "success" });
            resetQuery();
            subLoading.value = false;
            // equipopenDetail.value = false;
            handleprojectEditor2(response);
          })
          .catch(() => {
            subLoading.value = false;
          });
      } else {
        // if (params.weighingFile.length > 0) {
        //   params.weighingFile = params.weighingFile.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        // }
        // if (params.attachment.length > 0) {
        //   params.attachment = params.attachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        // }
        const params2 = {
          id: equipdata.value.id,
          projectNumber: equipdata.value.projectNumber,
          projectName: equipdata.value.projectName,
          projectType: equipdata.value.projectType,
          ownerId: equipdata.value.ownerId,
          ownerName: equipdata.value.ownerName,
          budgetAmount: equipdata.value.budgetAmount,
          planReceive: equipdata.value.planReceive,
          poList: equipdata.value.poList,
          deletePoIds: deletePoIds.value
        };
        projectupdate(params2)
          .then((response: any) => {
            PxMessage({ message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`, type: "success" });
            resetQuery();
            subLoading.value = false;
            // equipopenDetail.value = false;

            handleprojectEditor2(response);
          })
          .catch(() => {
            subLoading.value = false;
          });
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  //console.log(row);
  // const dictIds = [];
  // if (row.equipmentId != undefined) {
  //   dictIds.push(row.equipmentId);
  // } else {
  //   dictIds.push(...ids.value);
  // }
  PxMessageBox.confirm('是否确认删除"' + row.wasteName + '"？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await deletepush({ id: row.id });
      PxMessage({ message: "删除成功", type: "success" });
      getList();
    })
    .catch(() => {});
}
//出库
const handleprojectEditor = () => {
  console.log(ids.value);
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  projectqueryDetail({
    id: ids.value[0]
  }).then(res => {
    console.log(res);
    equipopenDetail.value = true;
    equipdata.value = res;
    equipdata.value.ownerId = Number(res.ownerId);
    deletePoIds.value = [];
  });
};

const handleprojectEditor2 = id => {
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  projectqueryDetail({
    id: id
  }).then(res => {
    console.log(res);
    equipopenDetail.value = true;
    equipdata.value = res;
    equipdata.value.ownerId = Number(res.ownerId);
    deletePoIds.value = [];
  });
};

/** 导出按钮操作 */
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
function handleExport() {
  let Token = getToken().accessToken || "";
  if (dateRange.value.length > 1) {
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E9%25A2%2584%25E7%25AE%2597%25E7%25AE%25A1%25E7%2590%2586%25E6%258A%25A5%25E8%25A1%25A8.cpt&token=${Token}&format=excel&extype=simple&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}&projectType=${props.projectType}&projectName=${queryParams.value.projectName}&productName=${queryParams.value.productName}&ownerName=${queryParams.value.ownerName}&vendor=${queryParams.value.vendor}&from=${dateRange.value[0]}&to=${dateRange.value[1]}`;
    window.location.href = url;
    console.log(url);
  } else {
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E9%25A2%2584%25E7%25AE%2597%25E7%25AE%25A1%25E7%2590%2586%25E6%258A%25A5%25E8%25A1%25A8.cpt&token=${Token}&format=excel&extype=simple&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}&projectType=${props.projectType}&projectName=${queryParams.value.projectName}&productName=${queryParams.value.productName}&ownerName=${queryParams.value.ownerName}&vendor=${queryParams.value.vendor}&from=&to=`;
    window.location.href = url;
    console.log(url);
  }
}

getList();
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  padding-top: 10px;
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  padding-top: 10px;
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 100px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs__header) {
  // padding-left: 6px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 230px !important;
}

:deep(.px-upload) {
  --px-upload-dragger-padding-horizontal: 18px;
}

:deep(.px-upload--picture-card) {
  --px-upload-picture-card-size: 93px;

  position: absolute;
}

.file-upload-dom {
  :deep(.px-upload-list--picture-card .px-upload-list__item) {
    position: relative;
    width: 96px;
    height: 96px;
    overflow: visible;

    .filebg {
      position: absolute;
      display: none;
      width: 96px;
      height: 96px;
      background: #0006;
    }

    .filedelect {
      margin: 35px;
      font-size: 22px !important;
      color: white;
      cursor: pointer;
    }

    &:hover {
      .filebg {
        display: block;
      }
    }

    .filesvg {
      position: absolute;
      top: 30px;
      left: 30px;
      font-size: 70px;
    }
  }

  :deep(.px-upload--picture-card) {
    --px-upload-picture-card-size: 93px;

    border: none;
  }
}

:deep(.px-upload-list--picture-card .px-upload-list__item) {
  width: 96px;
  height: 96px;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
      // th:nth-child(2) {
      //   font-size: 14px;
      //   font-weight: bold;
      //   color: #000;
      //   border-right: none;
      //   background-image: linear-gradient(to right, red, blue);
      // }
      // th:nth-child(3) {
      //   font-size: 14px;
      //   font-weight: bold;
      //   color: #000;
      //   border-right: none;
      //   background-image: linear-gradient(to right, #0400fc, yellow);
      // }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

:deep(.px-upload-list--picture-card > li:first-of-type) {
  margin-left: 104px;
}

:deep(.px-upload-list--picture-card) {
  min-height: 100px;
}

.level1 {
  width: 52px;
  height: 24px;
  margin: 0 auto;
  text-align: center;
  background: #ecfdf5;
  border: 1px solid #10b981;
  border-radius: 4px;
}

.level2 {
  width: 52px;
  height: 24px;
  margin: 0 auto;
  text-align: center;
  background: #fcf6ec;
  border: 1px solid #fda620;
  border-radius: 4px;
}

.level3 {
  width: 52px;
  height: 24px;
  margin: 0 auto;
  text-align: center;
  background: #eff6ff;
  border: 1px solid #3b82f6;
  border-radius: 4px;
}

:deep(.px-table__cell) {
  height: 36px;
  padding: 0;
  line-height: 36px;

  .cell {
    height: 36px;
    line-height: 36px;
  }
}

.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
      cursor: pointer;
    }
  }

  .import-bottle-upload {
    width: 100%;
    margin-bottom: 24px;
  }
}

.progressWrapper {
  display: flex;
  width: 100%;
}

.progressWrapper span {
  margin-right: 8px;
}

.progress {
  flex: 1;
  margin-right: 8px;
  font-size: 12px;
}
</style>
